package org.framework.lazy.cloud.network.heartbeat.server.init;

import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.protocol.token.AuthenticationTokenContext;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.netty.client.token.bucket.LazyNettyClientTokenBucket;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.netty.client.token.bucket.LazyNettyClientTokenBucketRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;


@Configuration
@Slf4j
public class InitAuthenticationToken implements CommandLineRunner {

    private final LazyNettyClientTokenBucketRepository lazyNettyClientTokenBucketRepository;

    public InitAuthenticationToken(LazyNettyClientTokenBucketRepository lazyNettyClientTokenBucketRepository) {
        this.lazyNettyClientTokenBucketRepository = lazyNettyClientTokenBucketRepository;
    }

    @Override
    public void run(String... args) throws Exception {
        try {
            LazyNettyClientTokenBucket lazyNettyClientTokenBucket = new LazyNettyClientTokenBucket();
            lazyNettyClientTokenBucket.setIsDeleted(false);
            for (LazyNettyClientTokenBucket nettyClientTokenBucket : lazyNettyClientTokenBucketRepository.findList(lazyNettyClientTokenBucket)
                    .getData()) {

                String clientId = nettyClientTokenBucket.getUsedByClientId();
                if (clientId != null) {
                    String appKey = nettyClientTokenBucket.getAppKey();
                    String appSecret = nettyClientTokenBucket.getAppSecret();
                    AuthenticationTokenContext.setAuthenticationToken(clientId, appKey, appSecret);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("初始化令牌桶失败:{}", e.getMessage());
        }

    }
}
